const { getUserInfo,getUserInfoById } = require('../service/user.service')

const { userFormateError, userAlreadyExited } = require('../constant/err.type')
const { userNoExited, passwordError } = require('../constant/err.type')


const userValidator = async (ctx, next) => {
	
	const {password, stuNum } = ctx.request.body
	if (!password || !stuNum) {
		console.error('用户名或密码或学号为空', ctx.request.body);
		ctx.app.emit('error', userFormateError, ctx)
		return
	}
	await next()
}

const verifyUser = async (ctx, next) => {
	
	const { stuNum } = ctx.request.body
	console.log({ stuNum });
	try {
		const res = await getUserInfo({ stuNum })

		if (res) {
			console.error('该账号已经存在')
			ctx.app.emit('error', userAlreadyExited, ctx)
			return
		}
	} catch (err) {
		console.error('获取用户信息错误', err)
		// ctx.app.emit('error', userRegisterError, ctx)
		return
	}

	await next()
}

const isAlreadyExistence = async (ctx, next) => {
	const { stuNum, password } = ctx.request.body
	try {
		const res = await getUserInfo({ stuNum })
		if (!res) {
			return ctx.app.emit('error', userNoExited, ctx)
		}
		if (password !== res.password) {
			return ctx.app.emit('error', passwordError, ctx)
		}
	} catch (err) {
		console.error('用户登录失败', err)
	}
	await next()

}

const verifyModify = async(ctx,next) =>{
	const id = ctx.request.query.id
	const {stuNum} = ctx.request.body
	const res = await getUserInfoById(id)
	if(stuNum == res.dataValues.stuNum){
		// 不用验证
		await next()
		console.log(true);
	}
	else{
		await verifyUser(ctx,next)
		console.log(false);
	}
}

module.exports = {
	userValidator,
	verifyUser,
	isAlreadyExistence,
	verifyModify
}